#!/bin/bash
# author    tyb

# 函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        exit 1
    fi
}

function network() {
    #超时时间
    local timeout=1

    #目标网站
    local target=www.baidu.com

    #获取响应状态码
    local ret_code
    ret_code=$(curl -I -s --connect-timeout ${timeout} ${target} -w "%{http_code}" | tail -n1)

    if [ "$ret_code" = "200" ]; then
        #网络畅通
        echo -e "\e[32m网络畅通==========>succeed\e[0m"
        return 0
    else
        #网络不畅通
        echo -e "\e[31m网络不畅通，请检查网络==========>succeed\e[0m"
        return 1
    fi

}

function validate_network() {
  local network=$1
  local network_pattern='^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(3[0-2]|[12]?[0-9])$'


  if [[ $network =~ $network_pattern ]]; then
    echo "Valid nerwork: $network"
  else
    echo "Invalid network: $network"
    exit 1
  fi
}

function validate_k8s_version() {
  local version=$1
  local version_pattern='^1\.23\.(0|([1-9]|1[0-7]))$'

  if [[ $version =~ $version_pattern ]]; then
    echo "Valid version: $version"
  else
    echo "Kubernetes version must be between 1.23.0 and 1.23.17."
    exit 1
  fi
}

function reset() {
  echo -e "\e[31mSince you have already installed k8s, installing it again will reset the previous installation\e[0m"
  while true; do
    read -rp "Are you sure you want to proceed? (y/n): " choice
    case "$choice" in
      [Yy])
        echo "开始重置k8s....."
        echo y | kubeadm reset >/dev/null 2>&1
        isgreen "重置k8s"
        break
        ;;
      [Nn])
        echo "Operation cancelled."
        exit 0
        ;;
      *)
        echo "Invalid input. Please enter 'y' to continue or 'n' to exit."
        ;;
    esac
  done
}

function print_help() {
  echo "Usage: $0 [OPTIONS]"
  echo "Options:"
  echo "  --help, -h                Display this help message."
  echo "  --hostname <host>         Specify the hostname. default: master"
  echo "  --pod-network <network>   Specify the pod network. default: 10.244.0.0/16"
  echo "  --version, -v <version>   Specify the Kubernetes version. default: 1.23.1"
  echo ""
  echo "calico安装方式："
  echo "  docker load -i calico-v3.26.1.tar.gz"
  echo "  kubectl apply -f calico.yaml"
  echo "ps: docker version is 20.10.24 !!!" 
}

# 获取主机名，需要输入用户名
while [[ $# -gt 0 ]]; do
  case "$1" in
    --help| -h)
        print_help
        exit 0
        ;;
    --hostname)
      if [[ -n "$2" ]]; then
        host="$2"
        shift 2
      else
        echo "Missing argument for -h option."
        exit 1
      fi
      ;;
    --pod-network)
      if [[ -n "$2" ]]; then
        validate_network "$2"
        network="$2"
        shift 2
      else
        echo "Missing argument for --pod-network option."
        exit 1
      fi
      ;;
    --version| -v)
      if [[ -n "$2" ]]; then
        validate_k8s_version "$2"
        version="$2"
        shift 2
      else
        echo "Missing argument for --version option."
        exit 1
      fi
      ;;
    --repo)
      if [[ -n "$2" ]]; then
        # 校验repository仓库的可用性
        repo="$2"
        shift 2
      else
        echo "Missing argument for --repo option."
        exit 1
      fi
      ;;
    *)
      echo "Invalid option: $1"
      exit 1
      ;;
  esac
done


# 全局变量
hostname=${host:-"master"}
ip=$(ip addr show eth0 | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | awk -F "/" '{print $1}')
network="${network:-"10.244.0.0/16"}"
version="${version:-"1.23.1"}"
repo="${repo:-"registry.aliyuncs.com/google_containers"}"

# 修改主机名为获取到的主机名
echo "修改主机名"
hostnamectl set-hostname "$hostname"
isgreen "修改主机名为：$hostname"

# 配置hosts解析文件
echo "配置hosts解析"
if grep -q "$hostname" /etc/hosts; then
    #解析存在进行修改
    sed -i "s/.*$hostname.*/$ip $hostname/g" /etc/hosts
    ping "$hostname" -c 1 >/dev/null 2>&1
    isgreen "配置hosts解析"
else
    # 解析不存在就新添加
    echo "$ip $hostname" >>/etc/hosts
    ping "$hostname" -c 1 >/dev/null 2>&1
    isgreen "配置hosts解析"
fi

# 安装kubelet、kubeadm、kubectl
echo "安装kubelet、kubeadm、kubectl"
if ! rpm -q kubelet-"$version"-0.x86_64 >/dev/null 2>&1; then
    yum install -y kubelet-"$version"-0.x86_64 kubectl-"$version"-0.x86_64 kubeadm-"$version"-0.x86_64 >/dev/null 2>&1
    isgreen "安装kubelet kubeadm kubectl"
else
    echo >/dev/null
    isgreen "安装kubelet kubeadm kubectl"
fi
systemctl enable kubelet --now >/dev/null 2>&1
isgreen "启动kubelet"


# 初始化k8s集群
echo "初始化k8s集群"
# 下载docker镜像
if [ -f /tmp/install-k8s ];then
  reset
fi

echo "开始初始化......"
kubeadm init --kubernetes-version="$version" --apiserver-advertise-address="$ip" --image-repository "$repo" --pod-network-cidr="$network" --ignore-preflight-errors=SystemVerification
isgreen "初始化"
if [ ! -f /tmp/install-k8s ];then
  touch /tmp/install-k8s 
fi


# 添加认证信息
echo "添加认证信息"
if [ -d "$HOME/.kube" ]; then
  rm -rf "$HOME/.kube"
fi
mkdir -p "$HOME/.kube"
sudo cp -i /etc/kubernetes/admin.conf "$HOME"/.kube/config
sudo chown "$(id -u)":"$(id -g)" "$HOME"/.kube/config
kubectl get nodes >/dev/null 2>&1
isgreen "添加认证信息"


# 配置k8s命令补全
echo "配置k8s命令补全"
if ! rpm -q bash-completion >/dev/null 2>&1; then
  yum install -y bash-completion >/dev/null 2>&1
fi
if ! grep -q kubectl ~/.bashrc; then
  echo 'source <(kubectl completion bash)' >>~/.bashrc
  # shellcheck source=/dev/null
  source ~/.bashrc
fi
isgreen "配置k8s命令补全"